﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Web.Services;
using System.Web.Script.Services;
using System.Collections;

public partial class MainPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetReminderData(); //Gets the subjects of all user's reminders and puts them into the ListBox
            fillComboBoxData(); //Fills the dialog box's dropdown menu data
        }
    }
    //Fills the dialog box's dropdown menu data
    private void fillComboBoxData()
    {
        int[] hours = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
        string[] minutes = { "00", "15", "30", "45" };
        string[] reoccuringTypes = { "", "Day", "Week", "Month", "Year" };
        hourCB.DataSource = hours;
        hourCB.DataBind();
        minuteCB.DataSource = minutes;
        minuteCB.DataBind();
        reoccuringTypeCB.DataSource = reoccuringTypes;
        reoccuringTypeCB.DataBind();
    }
    //Gets the subjects of all user's reminders and puts them into the ListBox
    private void GetReminderData()
    {
        /*
         * SQL Connection that grabs the logged in user's reminder data to load the listbox with
         */
        //Start
        string connectionStr = ConfigurationManager.ConnectionStrings[1].ConnectionString;
        string SQL = "SELECT subject FROM notifications WHERE created_by = @user AND fulfilled = 0";
        try
        {
            SqlConnection cn = new SqlConnection();
            SqlCommand command = new SqlCommand(SQL);
            SqlDataReader dataReader = null;
            cn.ConnectionString = connectionStr;
            cn.Open();
            command.Connection = cn;
            command.Parameters.Add("@user", SqlDbType.VarChar, 50).Value = Session["userID"];
            dataReader = command.ExecuteReader();

            while (dataReader.Read())
                remindersLB.Items.Add(dataReader.GetString(0));
        //End
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
    }
    //Method that takes information from Client-Side AJAX call and updates the fulfilled flag
    //Fulfilled flag determines if the reminder is needed or not
    [WebMethod]
    public static string RemoveReminder(string jReminder)
    {
        try
        {
            /*
             * SQL connection that updates the fulfilled flag to remove the reminder
             */
            //Start
            string user = HttpContext.Current.Session["userID"].ToString();
            string connectionStr = ConfigurationManager.ConnectionStrings[1].ConnectionString;
            string SQL = "UPDATE notifications SET fulfilled = @completed WHERE subject = @subj AND created_by = @user";
            SqlConnection cn = new SqlConnection();
            SqlCommand command = new SqlCommand(SQL);
            cn.ConnectionString = connectionStr;
            cn.Open();

            command.Connection = cn;
            command.Parameters.Add("@completed", SqlDbType.Bit, 1).Value = 1;
            command.Parameters.Add("@subj", SqlDbType.VarChar, 50).Value = jReminder;
            command.Parameters.Add("@user", SqlDbType.VarChar, 50).Value = user;
            int rows = command.ExecuteNonQuery();

            cn.Close();
            cn.Dispose();
            command.Dispose();
            return "Reminder Removed";
            //End
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }
    //Method that takes information from Client-Side AJAX call and updates the reminder data
    //All data is gathered by JavaScript and passed to C# parameters for processing
    [WebMethod]
    public static string UpdateReminder(string jSubject, string jReminderText, string jRemindDate, string jHour, string jMinute, string jAM_PM, string jReoccuringType, bool jRecursive, int jID)
    {
        try
        {
            /*
             * SQL connection that updates the reminder information provided by the user
             */
            //Start
            string connectionStr = ConfigurationManager.ConnectionStrings[1].ConnectionString;
            string SQL = "UPDATE notifications SET subject = @subj, reminder = @remind, reminder_date = @remindDate, reminder_time = @remindTime, is_recursive = @isRecursive, recursion_type = @recursionType " +
                        "WHERE ID = @id";

            SqlConnection cn = new SqlConnection();
            SqlCommand command = new SqlCommand(SQL);
            cn.ConnectionString = connectionStr;
            cn.Open();

            command.Connection = cn;
            command.Parameters.Add("@subj", SqlDbType.VarChar, 50).Value = jSubject;
            command.Parameters.Add("@remind", SqlDbType.VarChar, 160).Value = jReminderText;
            command.Parameters.Add("@remindDate", SqlDbType.VarChar, 50).Value = jRemindDate;
            command.Parameters.Add("@remindTime", SqlDbType.VarChar, 50).Value = String.Format("{0}:{1} {2}", jHour, jMinute, jAM_PM);
            command.Parameters.Add("@isRecursive", SqlDbType.Bit, 1).Value = jRecursive;
            command.Parameters.Add("@recursionType", SqlDbType.VarChar, 50).Value = jReoccuringType;
            command.Parameters.Add("@id", SqlDbType.Int).Value = jID;

            int rows = command.ExecuteNonQuery();
            cn.Close();
            cn.Dispose();
            command.Dispose();
            return "Reminder updated";
            //End
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }
    //Method that takes information from AJAX call and creates a new reminder
    //Informtion provided by JavaScript call that passes the data into the C# method's parameters
    [WebMethod]
    public static String CreateReminder(string jSubject, string jReminderText, string jRemindDate, string jHour, string jMinute, string jAM_PM, string jReoccuringType, bool jRecursive)
    {
        try
        {
            /*
             * SQL Connection that takes the data given by JavaScript to create a new reminder for the user
             */
            //Start
            DateTime date = DateTime.Now;
            string dateStr = date.Date.ToString("MM/dd/yyy");
            string subject = jSubject;
            string reminderText = jReminderText;
            string remindDateStr = jRemindDate;
            string timeStr = String.Format("{0}:{1}", jHour, jMinute);
            string am_pm = jAM_PM;
            string reminderType = jReoccuringType;
            bool isRecursive = jRecursive;
            string userID = HttpContext.Current.Session["userID"].ToString();

            string connectionStr = ConfigurationManager.ConnectionStrings[1].ConnectionString;
            string SQL = "INSERT INTO notifications (created_by, created_date, subject, reminder, reminder_date, reminder_time, is_recursive, recursion_type, fulfilled)" +
                        "VALUES(@createdBy,@createdDate,@subject,@reminder,@reminderDate,@reminderTime,@isRecursive,@recursionType,@fulfilled)";

            SqlConnection cn = new SqlConnection();
            SqlCommand command = new SqlCommand(SQL);
            cn.ConnectionString = connectionStr;
            cn.Open();
            command.Connection = cn;

            command.Parameters.Add("@createdBy", SqlDbType.VarChar, 50).Value = userID;
            command.Parameters.Add("@createdDate", SqlDbType.VarChar, 50).Value = dateStr;
            command.Parameters.Add("@subject", SqlDbType.VarChar, 50).Value = subject;
            command.Parameters.Add("@reminder", SqlDbType.VarChar, 160).Value = reminderText;
            command.Parameters.Add("@reminderDate", SqlDbType.VarChar, 50).Value = remindDateStr;
            command.Parameters.Add("@reminderTime", SqlDbType.VarChar, 50).Value = timeStr + " " + am_pm;
            command.Parameters.Add("@isRecursive", SqlDbType.Bit, 1).Value = isRecursive;
            command.Parameters.Add("@recursionType", SqlDbType.VarChar, 50).Value = reminderType;
            command.Parameters.Add("@fulfilled", SqlDbType.Bit, 1).Value = 0;
            int rows = command.ExecuteNonQuery();
            cn.Close();
            cn.Dispose();
            command.Dispose();
            //End
            return "Reminder Created";
        }
        catch (Exception e)
        {
            return e.Message;
        }
    }
    //Method that takes information from AJAX call and gets the SQL data to load into client
    //C# method pulls the data and send it back to client for processing
    [WebMethod]
    public static List<object> GetReminderData(string jReminderSubject)
    {
        /* SQL Connection that pulls all the reminder data about one reminder and puts them into a List object
         * Object is then sent to the client to be processed by JavaScript
         */
        //Start
        string[] data = null;
        int size = 0;
        List<object> list = new List<object>();
        string subject = jReminderSubject;
        string user = HttpContext.Current.Session["userID"].ToString();
        string connectionStr = ConfigurationManager.ConnectionStrings[1].ConnectionString;
        string SQL = "SELECT ID, subject, reminder, reminder_date, reminder_time, is_recursive, recursion_type FROM notifications " +
                        "WHERE created_by = @user AND subject = @subj";
        try
        {
            SqlConnection cn = new SqlConnection();
            SqlCommand command = new SqlCommand(SQL);
            SqlDataReader dataReader = null;
            cn.ConnectionString = connectionStr;
            cn.Open();
            command.Connection = cn;
            command.Parameters.Add("@user", SqlDbType.VarChar, 50).Value = user;
            command.Parameters.Add("@subj", SqlDbType.VarChar, 50).Value = subject;
            
            dataReader = command.ExecuteReader();
            while (dataReader.Read())
            {
                list.Add(dataReader.GetValue(0));
                list.Add(dataReader.GetValue(1));
                list.Add(dataReader.GetValue(2));
                list.Add(dataReader.GetValue(3));
                list.Add(dataReader.GetValue(4));
                list.Add(dataReader.GetValue(5));
                list.Add(dataReader.GetValue(6));
            }
                
            for (int x = 0; x < list.Count; x++)
                data[x] = (string) list[x];
        //End
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
        return list;
    }
}